<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin=false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin=true" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <Form class="form" ref="formCom" :validation-schema="schema" v-slot="{errors}" autocomplete="off">
      <!-- 账号登录 -->
      <template v-if="!isMsgLogin">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field type="text" placeholder="请输入账号" :class="{error:errors.account}" v-model="form.account" name="account"/>
          </div>
          <!-- 错误提示 -->
          <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{errors.account}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <Field type="password" placeholder="请输入密码" :class="{error:errors.password}" v-model="form.password" name="password"/>
          </div>
          <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{errors.password}}</div>
        </div>
      </template>
      <!-- 手机登录 -->
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <Field type="text" placeholder="请输入手机" :class="{error:errors.mobile}" v-model="form.mobile" name="mobile"/>
          </div>
          <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" />{{errors.mobile}}</div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <Field type="text" placeholder="请输入验证码" :class="{error:errors.code}" v-model="form.code" name="code"/>
            <span class="code" @click="send">{{time===0?'发送验证码':`${time}秒后再发送`}}</span>
          </div>
          <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{errors.code}}</div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
          <!-- 自定义组件校验需要用 as属性-->
          <Field as="XtxCheckbox" v-model="form.isAgree" name="isAgree"/>
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
          <div class="error" v-if="errors.isAgree">
          <i class="iconfont icon-warning" />
          {{errors.isAgree}}
        </div>
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </Form>
    <div class="action">
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
        <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
      </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { onUnmounted, reactive, ref, watch } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import Message from '@/components/library/Message'
import { userAccountLogin, userMobileLogin, userMobileLoginMsg } from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
// import { useIntervalFn } from '@vueuse/core'
export default {
  name: 'LoginForm',
  components: { Form, Field },
  setup (pros) {
    // 控制显示账号&手机登录数据,默认账号登录
    const isMsgLogin = ref(false)

    // 表单数据信息
    const form = reactive({
      isAgree: true,
      account: null,
      password: null,
      mobile: null,
      code: null
    })

    // 校验规则对象
    const mySchema = {
      account: schema.account,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      isAgree: schema.isAgree
    }
    // vee-validate插件校验规则
    // 1、导入插件，并且Form, Field分别替换对应form、input标签
    // 2、制定表单数据对象，里面存当前文本框的值；制定校验规则对象，每个校验规则以函数形式书写，校验规则函数要对应表单数据属性名
    // 3、校验规则函数通过时，返回return，反之返回错误信息
    // 4、双向数据绑定文本框的值；每个Field都加上校验规则，赋值给name属性
    // 5、给Form标签的validation-schema属性添加上校验规则对象；利用插槽v-slot="{errors}"，每个Field标签利用errors.【校验函数名】显示错误信息

    // 监听表单切换，表单重置
    const formCom = ref(null)
    watch(isMsgLogin, () => {
      // 重置表单数据
      form.isAgree = true
      form.account = null
      form.password = null
      form.mobile = null
      form.code = null
      // vee-validate提供Form元素resetForm()函数重置表单验证规则
      formCom.value.resetForm()
    })

    // 监听登录事件
    const store = useStore()
    const router = useRouter()
    const route = useRoute()
    const login = async () => {
      // vee-validate提供Form元素validate()函数验证整体表单，返回是promise对象，里面是布尔值
      const valid = await formCom.value.validate()
      let data = null
      // 表单认证通过
      if (valid) {
        // 利用try...catch捕捉错误
        try {
          if (isMsgLogin.value) {
            // 手机登录
            const { mobile, code } = form
            data = await userMobileLogin({ mobile, code })
          } else {
            // 账号登录
            const { account, password } = form
            data = await userAccountLogin({ account, password })
          }
          // 保存在vuex中，自动保存在本地
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
          // 需要先合并完购物车
          store.dispatch('cart/mergeCart').then(() => {
            // 如果是其他跳转过来的，需要跳转回去
            router.push(route.query.redirectUrl || '/')
            // 成功消息提示
            Message({ type: 'success', text: '登录成功' })
          })
        } catch (e) {
          // 登录失败提示
          if (e.response.data) {
            Message({ type: 'error', text: e.response.data.message || '登录失败' })
          }
        }
      }
    }

    // 利用useIntervalFn定时器函数,(计时逻辑回调，间距，是否自动开启)
    // pause 暂停 resume 开始,
    // const time = ref(0)
    // const { pause, resume } = useIntervalFn(() => {
    //   // 倒计时60秒，倒计时完毕可重新发送请求
    //   time.value--
    //   if (time.value <= 0) {
    //     pause()
    //   }
    // }, 1000, false)

    // // 组件销毁时，清定时器
    // onUnmounted(() => {
    //   pause()
    // })

    // 点击发送验证码事件
    const time = ref(0)
    let timer = null
    const send = async () => {
      // 调用校验规则，得到校验结果对象
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        // 合法手机则发送请求,并且倒计时要为0
        if (time.value === 0) {
          await userMobileLoginMsg(form.mobile)
          Message({ type: 'success', text: '发送成功' })
          // 每次都先清除定时器
          clearInterval(timer)
          time.value = 60
          timer = setInterval(() => {
            time.value--
            if (time.value <= 0) {
              // 为0时停止倒计时
              clearInterval(timer)
            }
          }, 1000)
        }
      } else {
        // 利用vee-validate提供的setFieldError(规则名，错误信息)，触发错误消息提示
        formCom.value.setFieldError('mobile', valid)
      }
    }

    // 组件销毁时清掉倒计时
    onUnmounted(() => {
      clearInterval(timer)
    })

    return { isMsgLogin, form, schema: mySchema, formCom, login, send, time }
  }
}
</script>

<style lang="less" scoped>
 // 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,&:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>
